package com.valuegroup.smarttodo.ui.todo.habit;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.valuegroup.smarttodo.R;
import com.valuegroup.smarttodo.common.BaseViewHolder;
import com.valuegroup.smarttodo.common.CommonRecyclerAdapter;
import com.valuegroup.smarttodo.data.ServiceFactory;
import com.valuegroup.smarttodo.data.model.AppStatus;
import com.valuegroup.smarttodo.data.model.HabitOrder;
import com.valuegroup.smarttodo.data.model.HabitOrderRelate;
import com.valuegroup.smarttodo.data.vo.HabitItemVo;
import com.valuegroup.smarttodo.ui.BaseActivity;
import com.valuegroup.smarttodo.plugins.pickdialog.DateUtils;
import com.valuegroup.smarttodo.util.AlertUtils;

import java.util.List;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 设置习惯清单
 */
public class HabitOrderActivity extends BaseActivity {

    @BindView(R.id.btnBack)
    ImageButton btnBack;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btnGoForm)
    LinearLayout btnGoForm;
    @BindView(R.id.layoutFilter)
    LinearLayout layoutFilter;
    @BindView(R.id.labFilter)
    TextView labFilter;
    @BindView(R.id.editSearch)
    EditText editSearch;
    @BindView(R.id.layoutSearch)
    LinearLayout layoutSearch;
    @BindView(R.id.labTitle)
    TextView labTitle;
    @BindView(R.id.labTimeQuantum)
    TextView labTimeQuantum;
    @BindView(R.id.btnGoFind)
    ImageView btnGoFind;

    private HabitOrderAdapter adapter;
    private PopupMenu filterMenu;
    private Long DATA_ID;
    private Integer DATA_POSITION;
    private HabitOrder DATA;
    private int countSize = 0;
    private int filterType = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_habitorder);
        ButterKnife.bind(this);

        initView();
        initData();
    }

    private void initData() {
        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        DATA_POSITION = getIntent().getIntExtra(PARAMS_POSITION, 0);
        DATA = ServiceFactory.getInstance().getHabitService().getHabitOrderDao().load(DATA_ID);

        if (DATA_ID != 0 && DATA == null) {
            AlertUtils.showToast(getApplicationContext(), R.string.not_found_record);
            finish();
            return;
        }

        if (DATA_ID == 0) {
            DATA = ServiceFactory.getInstance().getHabitService().getDefaultHabitOrder();
        }

        // 时段及提醒频率
        labTitle.setText(DATA.getTitle());
        String timeQuantum = String.format(getResources().getString(R.string.habit_time_quantum),
                DateUtils.date2str(DATA.getStartTime(), DateUtils.F21),
                DateUtils.date2str(DATA.getEndTime(), DateUtils.F21));
        if (DATA.getOpenRemind()) {
            timeQuantum += String.format(getResources().getString(R.string.habit_time_quantum_2), DATA.getRemindInterval());
        }
        labTimeQuantum.setText(timeQuantum);

        // 过滤标签
        labFilter.setText(String.format(getResources().getString(R.string.habit_filter), getResources().getString(R.string.habit_filter_m1), countSize));
    }

    private void initView() {
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        adapter = new HabitOrderAdapter(this, loadData(null));
        recyclerView.setAdapter(adapter);

        filterMenu = new PopupMenu(this, layoutFilter);
        filterMenu.inflate(R.menu.menu_habit_filter);
        filterMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.habit_item1:
                        // 全部
                        filterType = 0;
                        break;
                    case R.id.habit_item2:
                        // 已选
                        filterType = 1;
                        break;
                    case R.id.habit_item3:
                        // 未选
                        filterType = 2;
                        break;
                }

                // 更新list列表
                refreshAllData(null);

                // 获取item数量
                labFilter.setText(String.format(getResources().getString(R.string.habit_filter), item.getTitle(), countSize));
                return true;
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    refreshAllData(v.getText().toString());
                }
                // 返回true，保留软键盘。false，隐藏软键盘
                return true;
            }
        });

        editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (!TextUtils.isEmpty(s.toString())) {
                    refreshAllData(s.toString());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        editSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    // 得到焦点

                    // 光标移动到末尾
                    editSearch.setSelection(editSearch.getText().length());

                    // 弹出键盘
                    InputMethodManager inputManager = (InputMethodManager) editSearch.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editSearch, 0);
                }
            }
        });

    }

    /**
     * 更新列表所有数据
     */
    private void refreshAllData(String searchKey) {
        // 刷新列表数据
        adapter.refreshListData(loadData(searchKey));
        // 平移到相关位置
        recyclerView.smoothScrollToPosition(0);
    }

    private List<HabitItemVo> loadData(String searchKey) {
        DATA_ID = getIntent().getLongExtra(PARAMS_KEY, 0);
        List<HabitItemVo> data = ServiceFactory.getInstance().getHabitService().findHabitItemVoForOrder(DATA_ID, filterType, searchKey);
        countSize = data.size();
        return data;
    }

    @OnClick({R.id.btnBack, R.id.btnGoForm, R.id.layoutFilter, R.id.btnGoFind})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnBack:
                setCloseParams();
                finishAfterTransition();
                break;
            case R.id.btnGoForm:
                Intent intent1 = new Intent(view.getContext(), HabitOrderSetActivity.class);
                intent1.putExtra(PARAMS_KEY, DATA.getId());
                intent1.putExtra(PARAMS_POSITION, DATA_POSITION);
                startActivityForResult(intent1, 1001);
                break;
            case R.id.layoutFilter:
                filterMenu.show();
                break;
            case R.id.btnGoFind:
                if (View.GONE == layoutFilter.getVisibility()) {
                    layoutFilter.setVisibility(View.VISIBLE);
                    layoutSearch.setVisibility(View.GONE);

                    btnGoFind.setImageResource(R.drawable.ic_find_gray3);

                    // 恢复全部数据
                    refreshAllData(null);
                } else {
                    layoutFilter.setVisibility(View.GONE);
                    layoutSearch.setVisibility(View.VISIBLE);
                    editSearch.setText(null);
                    btnGoFind.setImageResource(R.drawable.ic_close_gray3);

                    /**
                     * 动态给EditText获得焦点并弹起软键盘
                     */
                    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                    editSearch.setFocusable(true);
                    editSearch.setFocusableInTouchMode(true);
                    editSearch.requestFocus();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(editSearch, 0);
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (data != null && data.getBooleanExtra(DEL_TAG, false)) {
            // 子页面因删除关闭，当前页面也附带关闭
            finishAfterTransition();
            return;
        }
        initData();
        refreshAllData(null);
    }

    @Override
    public void onBackPressed() {
        setCloseParams();
        super.onBackPressed();
    }

    private void setCloseParams() {
        Intent intent = new Intent();
        intent.putExtra(PARAMS_POSITION, DATA_POSITION);
        intent.putExtra(PARAMS_KEY, DATA_ID);
        setResult(RESULT_OK, intent);
    }

    public class HabitOrderAdapter extends CommonRecyclerAdapter<HabitItemVo> {


        public HabitOrderAdapter(Context context, List<HabitItemVo> data) {
            super(context, data);
            setMainLayoutId(R.layout.item_habitorder);
            setBottomLayoutId(R.layout.item_default_bottom);
        }

        private void changeBtnOperationView(BaseViewHolder v, HabitItemVo data) {
            // 变更操作按钮视图内容
            v.setTextAndColor(R.id.btnOperation,
                    getResources().getString(data.isJoin() ? R.string.op_remove : R.string.op_join),
                    ContextCompat.getColor(getmContext(), data.isJoin() ? R.color.colorWarn : R.color.colorLink));


            if (data.isJoin() && data.getRelateId() != null) {
                HabitOrderRelate r = ServiceFactory.getInstance().getHabitService().getHabitOrderRelateDao().load(data.getRelateId());

                String repeatStr = "";
                switch (r.getRepeatType()) {
                    case AppStatus.RepeatType.EVERYDAY:
                        repeatStr = "每天";
                        break;
                    case AppStatus.RepeatType.EVERYWEEK:
                        repeatStr = "每周(" + DateUtils.ARR_WEEKS[r.getRepeatFirst()] + ")";
                        break;
                    case AppStatus.RepeatType.WORKDAY:
                        repeatStr = "工作日";
                        break;
                    case AppStatus.RepeatType.UNWORKDAY:
                        repeatStr = "非工作日";
                        break;
                    case AppStatus.RepeatType.EVERYMONTH:
                        repeatStr = "每月(" + r.getRepeatFirst() + "日)";
                        break;
                }

                v.setText(R.id.labTarget, String.format(getResources().getString(R.string.habit_lab_target), repeatStr, DateUtils.date2str(r.getBeginDt(), DateUtils.F40), DateUtils.date2str(r.getEndDt(), DateUtils.F40)));
            }

            v.setViewVisibility(R.id.labTarget, data.isJoin());
        }

        @Override
        public void bindHeadView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindBottomView(BaseViewHolder v, int position) {

        }

        @Override
        public void bindMainView(BaseViewHolder v, int position) {
            HabitItemVo data = getData(position);
            // 添加与移除习惯关联
            TextView btnOperation = v.getView(R.id.btnOperation);
            btnOperation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (data.isJoin()) {
                        AlertUtils.removeJoinDialog(getmContext(), String.format(getResources().getString(R.string.alt_remove_habit_join), data.getTitle()), new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ServiceFactory.getInstance().getHabitService().doRmoveJoin(data.getRelateId());
                                data.setJoin(false);
                                data.setRelateId(null);
                                changeBtnOperationView(v, data);
                            }
                        });

                    } else {
                        HabitOrderRelate r = ServiceFactory.getInstance().getHabitService().doJoin(data.getOrderId(), data.getId());
                        if (r != null) {
                            data.setJoin(true);
                            data.setRelateId(r.getId());
                            changeBtnOperationView(v, data);
                        }
                    }
                }
            });

            v.getView(R.id.labTarget).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(HabitOrderActivity.this, HabitRuleSetActivity.class);
                    intent.putExtra(PARAMS_KEY, data.getRelateId());
                    intent.putExtra("orderId", DATA.getId());
                    intent.putExtra(PARAMS_POSITION, DATA_POSITION);
                    startActivityForResult(intent, 1001);

                    // showDialog();
                }
            });


            // 初始化内容
            String subTime = String.format(getResources().getString(R.string.lab_minute), data.getPreMinute());
            v.setText(R.id.labTitle, data.getTitle());
            v.setText(R.id.labSubtitle, data.getSubTitle());
            v.setText(R.id.labTime, subTime);
            //v.setImageResource(R.id.tagEmoji, data.getEmoji());

            // 优先级
            ImageView imgQuadrant = v.getView(R.id.tagQuadrant);
            imgQuadrant.setImageResource(AppStatus.QuadrantTagArr[data.getQuadrant()]);

            changeBtnOperationView(v, data);
        }


        @Override
        public void bindAppendView(BaseViewHolder v, int position) {

        }


    }

}
